package cn.itcast.bos.web.action;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import javax.ws.rs.core.MediaType;

import org.apache.commons.lang3.StringUtils;
import org.apache.cxf.jaxrs.client.WebClient;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Controller;

import cn.itcast.bos.constant.Constants;
import cn.itcast.bos.domain.base.Area;
import cn.itcast.bos.domain.base.FixedArea;
import cn.itcast.bos.service.FixedAreaService;
import cn.itcast.bos.web.action.common.BaseAction;
import cn.itcast.crm.domain.Customer;

@ParentPackage(value="json-default")
@Namespace("/")
@Controller
@Scope("prototype")
public class FixedAreaAction extends BaseAction<FixedArea> {
	String url="http://localhost:9002"+"/crm_management";
	@Autowired
	private FixedAreaService fixedAreaService;
	
	@Action(value="fixedArea_save",results={@Result(name="success",type="redirect",location="./pages/base/fixed_area.html")})
	public String save(){
		fixedAreaService.save(model);
		return SUCCESS;
	}
	
	/**首页查询（分页）*/
	@Action(value="fixedArea_pageQuery",results={@Result(name="success",type="json")})
	public String pageQuery(){
		// 带有条件的分页查询
		Pageable pageable = new PageRequest(page-1, rows);// 当前页(0作为基页数)、当前页最多显示的记录数
		//条件查询
		Specification<FixedArea> specification = new Specification<FixedArea>() {
			
			/**
			 * 传递：
			 * 		Root<Courier> root：（连接语句的时候需要字段，获取字段的名称）代表Criteria查询的根对象，Criteria查询的查询根定义了实体类型，能为将来导航获得想要的结果，它与SQL查询中的FROM子句类似
			 * 		CriteriaQuery<?> query： （简单的查询可以使用CriteriaQuery）代表一个specific的顶层查询对象，它包含着查询的各个部分，比如：select 、from、where、group by、order by等
			 * 		CriteriaBuilder cb：（复杂的查询可以使用CriteriaBuilder构建）用来构建CritiaQuery的构建器对象
			 * 返回：Predicate：封装查询条件
			 * 
			 */
			@Override
			public Predicate toPredicate(Root<FixedArea> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
				// 封装查询条件
				Predicate predicate = null;
				List<Predicate> list = new ArrayList<Predicate>();
				// 定区编码
				if(StringUtils.isNotBlank(model.getId())){
					Predicate p = cb.equal(root.get("id").as(String.class), model.getId());// id = ?
					list.add(p);
				}
				// 公司
				if(StringUtils.isNotBlank(model.getCompany())){
					Predicate p = cb.like(root.get("company").as(String.class), "%"+model.getCompany()+"%");// company like ?
					list.add(p);
				}
				
				// 此时表示有条件
				if(list!=null && list.size()>0){
					Predicate [] restrictions = new Predicate[list.size()];
					predicate = cb.and(list.toArray(restrictions));
				}
				
				return predicate;
				
			}
		};
		
		Page<FixedArea> page = fixedAreaService.findPageQueryBySpecfication(pageable,specification);
		pushPageDataToValueStack(page);
		return SUCCESS;
	}
	
	/**查询没有关联定区的客户*/
	@Action(value="fixedArea_findNoAssociationCustomers",results={@Result(name="success",type="json")})
	public String findNoAssociationCustomers(){
		
		Collection<? extends Customer> collection = WebClient.create(url+"/services/customerService")
					.path("/findNoAssociationCustomers")
					.accept(MediaType.APPLICATION_JSON)
					.getCollection(Customer.class);
		ServletActionContext.getContext().getValueStack().push(collection);
		return SUCCESS;
	}
	
	/**查询当前定区关联的客户*/
	@Action(value="fixedArea_findHasAssociationFixedAreaCustomers",results={@Result(name="success",type="json")})
	public String findHasAssociationFixedAreaCustomers(){
		
		Collection<? extends Customer> collection = WebClient.create(url+"/services/customerService")
					.path("/findHasAssociationFixedAreaCustomers/"+model.getId())
					.accept(MediaType.APPLICATION_JSON)
					.getCollection(Customer.class);
		ServletActionContext.getContext().getValueStack().push(collection);
		return SUCCESS;
	}
	
	//存放客户ID
	private String [] customerIds;
	
	public void setCustomerIds(String[] customerIds) {
		this.customerIds = customerIds;
	}
	
	/**定区关联客户的保存*/
	@Action(value="fixedArea_associationCustomersToFixedArea",results={@Result(name="success",type="redirect",location="./pages/base/fixed_area.html")})
	public String associationCustomersToFixedArea(){
		// 将客户ID，变成字符串，中间使用逗号分开
		String customerIdStr = StringUtils.join(customerIds, ",");
		// 定区id
		String fixedAreaId = model.getId();
		WebClient.create(url+"/services/customerService/associationCustomersToFixedArea?customerIdStr="+customerIdStr+"&fixedAreaId="+fixedAreaId)
				// 如果使用QueryParam传递，此时不能通过path的方法完成
				//.path("/associationCustomersToFixedArea?customerIdStr="+customerIdStr+"&fixedAreaId="+fixedAreaId)
				.put(null);// null表示不接受对象，通过QueryParam接受
		
		return SUCCESS;
	}
	
	// 存放快递员ID
	private String courierId;
	
	public void setCourierId(String courierId) {
		this.courierId = courierId;
	}
	// 存放收派时间ID
	private String takeTimeId;

	public void setTakeTimeId(String takeTimeId) {
		this.takeTimeId = takeTimeId;
	}

	/**定区关联快递员*/
	@Action(value="fixedArea_associationCourierToFixedArea",results={@Result(name="success",type="redirect",location="./pages/base/fixed_area.html")})
	public String associationCourierToFixedArea(){
		// 定区id
		String fixedAreaId = model.getId();
		fixedAreaService.associationCourierToFixedArea(fixedAreaId,courierId,takeTimeId);
		// 快递员ID
		return SUCCESS;
	}
}
